/************************************************
 * Author       :   XXY
 * Blog         :   https://www.cnblogs.com/jzyl
 * Gitee        :   https://gitee.com/xiaobaichong
 * Email        :   1047185209@QQ.com
 * FileName     :   MessagePageCanvas.cs
 * CreateData   :   2023/10/18 13:45:52
 * UnityVersion :   2021.3.20f1c1
 * Description  :   页面 Brower
************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Cysharp.Threading.Tasks;
using Sirenix.OdinInspector;
using UnityEngine.Events;

namespace Main.Framework
{
    public class MessagePageCanvas : MonoBehaviour
    {
        #region 预制件
        [SerializeField][FoldoutGroup("预制件")] GameObject optionPrefab;
        [SerializeField][FoldoutGroup("预制件")] GameObject textPrefab;
        [SerializeField][FoldoutGroup("预制件")] GameObject imagePrefab;
        #endregion
        #region 字段
        [SerializeField][FoldoutGroup("字段")] RectTransform leftContent;
        [SerializeField][FoldoutGroup("字段")] RectTransform rightContent;
        [SerializeField][FoldoutGroup("字段")] Text titleTxT;
        [SerializeField][FoldoutGroup("字段")] Button closeBtn;
        [SerializeField][FoldoutGroup("字段")] ScrollRect scrollRect;
        #endregion
        #region 配置表
        [FoldoutGroup("页面数据配置表")][SerializeField, LabelText("大标题:"), LabelWidth(50)] string titleName;
        [Space]
        [FoldoutGroup("页面数据配置表")][SerializeField, HideLabel, TableList(AlwaysExpanded = true, ShowIndexLabels = true, HideToolbar = true)] List<Page> pages = new List<Page>();
        #endregion
        #region 类
        [Serializable]
        public class Page   // 页面表
        {
            [Required("请输入标题")]
            [LabelText("标题:"), LabelWidth(40), VerticalGroup("页面数据")]
            public string title = "标题";
            [LabelText("内容"), TableList(DrawScrollView = true, ShowIndexLabels = true, MinScrollViewHeight = 450), VerticalGroup("页面数据")]
            public List<PageData> pageDatas = new List<PageData>();
        }
        [Serializable]
        public class PageData   // 页面数据
        {
            [PreviewField(95, Alignment = ObjectFieldAlignment.Center), TableColumnWidth(100, Resizable = false), HideLabel]
            public Sprite sprite;
            [TextArea(6, 6), HideLabel]
            public string msg;
            [TableColumnWidth(50, Resizable = false), HideLabel]
            public bool isTitle;
        }
        public class OptionPrefab
        {
            ButtonToggle toggle;
            public OptionPrefab(GameObject target, string title, UnityAction<int> OnToggleChange)
            {
                toggle = target.GetComponent<ButtonToggle>();
                toggle.onClick.RemoveAllListeners();
                toggle.onClick.AddListener((arg) =>
                {
                    if (arg)
                    {
                        OnToggleChange?.Invoke(toggle.transform.GetSiblingIndex());
                    }
                });
                toggle.transform.Find("Label").GetComponent<Text>().text = title;
            }
        }
        public class TextPrefab     // 文本预制件
        {
            private Text text;
            private string msg;
            public TextPrefab(GameObject target, string msg, int fontSize = 12)
            {
                text = target.GetComponent<Text>();
                this.msg = msg;
                text.fontSize = fontSize;
                text.text = this.msg;
                Refresh();
            }
            private async void Refresh()
            {
                await UniTask.Delay(100);
                float winWidth = text.transform.parent.GetComponent<RectTransform>().rect.width - 30;
                text.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, winWidth);
                text.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, text.preferredHeight);
            }
        }
        public class ImagePrefab
        {
            private Image image;
            public ImagePrefab(GameObject target, Sprite sprite)
            {
                image = target.GetComponent<Image>();
                image.sprite = sprite;
                Refresh();
            }
            private async void Refresh()
            {
                await UniTask.Delay(100);
                float winWidth = image.transform.parent.GetComponent<RectTransform>().rect.width - 30;
                RectTransform rect = image.GetComponent<RectTransform>();
                float texWidth = image.sprite.texture.width;
                float texHight = image.sprite.texture.height;
                if (texWidth < winWidth)
                {
                    rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, texWidth);
                    rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, texHight);
                }
                else
                {
                    rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, winWidth);
                    rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, winWidth * texHight / texWidth);
                }
            }
        }
        #endregion
        List<List<GameObject>> books = new List<List<GameObject>>();
        private void Awake()
        {
            optionPrefab.SetActive(false);
            textPrefab.SetActive(false);
            imagePrefab.SetActive(false);
            titleTxT.text = titleName;
            closeBtn.onClick.AddListener(OnClose);
            // 刷新列表
            Refresh();
        }
        private void Generate()  // 实例化
        {
            // 生成
            for (int i = 0; i < pages.Count; i++)
            {
                // 选项
                GameObject option = Instantiate(optionPrefab, leftContent);
                new OptionPrefab(option, pages[i].title, OnToggleChange);
                option.gameObject.SetActive(true);
                List<GameObject> contents = new List<GameObject>();
                // 内容
                for (int n = 0; n < pages[i].pageDatas.Count; n++)
                {
                    PageData data = pages[i].pageDatas[n];
                    GameObject target = null;
                    if (data.sprite != null)
                    {
                        target = Instantiate(imagePrefab, rightContent);
                        new ImagePrefab(target, data.sprite);
                    }
                    else
                    {
                        target = Instantiate(textPrefab, rightContent);
                        new TextPrefab(target, data.msg, data.isTitle ? 48 : 24);
                    }
                    target.gameObject.SetActive(true);
                    contents.Add(target);
                }
                books.Add(contents);
            }
        }
        private void OnToggleChange(int index)
        {
            for (int i = 0; i < books.Count; i++)
            {
                foreach (var content in books[i])
                {
                    content.SetActive(i == index - 1);
                }
            }
            scrollRect.verticalNormalizedPosition = 1;
        }

        #region 方法
        /// <summary>
        /// 页面数量
        /// </summary>
        public int PageCount => leftContent.childCount - 1;
        /// <summary>
        /// 显示页面窗口
        /// </summary>
        public void Show(int pageIndex = 0)
        {
            transform.GetChild(0).gameObject.SetActive(true);
            leftContent.GetChild(pageIndex + 1).GetComponent<ButtonToggle>().IsOn = true;
        }
        /// <summary>
        /// 添加一个页面
        /// </summary>
        private void AddPage(Page page)
        {
            // 添加 页面
            pages.Add(page);
            // 刷新 添加内容
            Refresh();
        }
        /// <summary>
        /// 删除序号为indexPage的页面
        /// </summary>
        private void DelPage(int indexPage)
        {
            if (pages.Count > indexPage)
            {
                // 删除 页面
                pages.RemoveAt(indexPage);
                // 刷新 添加内容
                Refresh();
            }
        }
        /// <summary>
        /// 获取指定页面
        /// </summary>
        private Page GetPage(int indexPage)
        {
            return pages[indexPage];
        }/// <summary>
         /// 刷新页面
         /// </summary>
        private void Refresh()
        {
            // 删除所有
            for (int i = 0; i < books.Count; i++)
            {
                while (books[i].Count > 0)
                {
                    Destroy(books[i][0]);
                    books[i].RemoveAt(0);
                }
            }
            books.Clear();
            while (leftContent.childCount > 1)
            {
                DestroyImmediate(leftContent.GetChild(1).gameObject);
            }
            // 生成列表对象
            Generate();
            // 默认打开第一页
            if (leftContent.childCount > 1)
            {
                leftContent.GetChild(1).GetComponent<ButtonToggle>().IsOn = true;
            }
        }
        private void OnClose()
        {
            transform.GetChild(0).gameObject.SetActive(false);
        }
        #endregion

        #region EDITOR
#if UNITY_EDITOR
        [Button("添加"), HorizontalGroup]
        private void AddPage()
        {
            pages.Add(new Page());
        }
        [Button("空除NULL"), HorizontalGroup]
        private void ClearNULL()
        {
            for (int i = 0; i < pages.Count;)
            {
                Page page = pages[i];
                for (int n = 0; n < page.pageDatas.Count;)
                {
                    PageData data = page.pageDatas[n];
                    if (string.IsNullOrWhiteSpace(data.msg) && data.sprite == null)
                    {
                        page.pageDatas.RemoveAt(n);
                    }
                    else
                    {
                        n++;
                    }
                }
                if (string.IsNullOrWhiteSpace(page.title) || page.pageDatas.Count == 0)
                {
                    pages.RemoveAt(i);
                }
                else
                {
                    i++;
                }
            }
        }
#endif
        #endregion
    }
}
